package ${packagePrefix}.infrastructure.adapter;

import ${packagePrefix}.domain.model.${tableName?lower_case}.${domainObjectName};
import ${packagePrefix}.domain.shared.ExternalSystemException;
import ${packagePrefix}.infrastructure.adapter.dto.External${domainObjectName}DTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * ${entityComment}外部系统适配器
 * 防腐层模式实现，用于隔离外部系统与领域模型，防止外部系统变化污染领域模型
 */
@Component
public class ${domainObjectName}Adapter {
    
    private static final Logger logger = LoggerFactory.getLogger(${domainObjectName}Adapter.class);
    
    @Autowired
    private RestTemplate restTemplate;
    
    @Value("<#noparse>${external.service.url:http://external-service}</#noparse>")
    private String externalServiceUrl;
    
    @Value("<#noparse>${external.service.token:}</#noparse>")
    private String serviceToken;
    
    /**
     * 从外部系统获取${entityComment}信息
     *
     * @param externalId 外部系统ID
     * @return 领域对象
     */
    public ${domainObjectName} getFromExternalSystem(String externalId) {
        try {
            // 构建请求头
            HttpHeaders headers = new HttpHeaders();
            headers.set("Authorization", "Bearer " + serviceToken);
            
            // 发起请求
            String url = externalServiceUrl + "/api/" + "${tableName?lower_case}" + "/" + externalId;
            ResponseEntity<External${domainObjectName}DTO> response = restTemplate.exchange(
                url,
                HttpMethod.GET,
                new HttpEntity<>(headers),
                External${domainObjectName}DTO.class
            );
            
            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
                // 将外部系统DTO转换为领域对象
                return convertToDomainObject(response.getBody());
            } else {
                logger.error("Failed to get ${domainObjectName} from external system. Response: {}", response);
                throw new ExternalSystemException("Failed to get data from external system");
            }
            
        } catch (Exception e) {
            logger.error("Error calling external system", e);
            throw new ExternalSystemException("Error calling external system: " + e.getMessage());
        }
    }
    
    /**
     * 将${entityComment}信息同步到外部系统
     *
     * @param ${domainObjectName?uncap_first} 领域对象
     * @return 是否同步成功
     */
    public boolean syncToExternalSystem(${domainObjectName} ${domainObjectName?uncap_first}) {
        try {
            // 转换为外部系统DTO
            External${domainObjectName}DTO dto = convertToExternalDTO(${domainObjectName?uncap_first});
            
            // 构建请求头
            HttpHeaders headers = new HttpHeaders();
            headers.set("Authorization", "Bearer " + serviceToken);
            headers.set("Content-Type", "application/json");
            
            // 发起请求
            String url = externalServiceUrl + "/api/" + "${tableName?lower_case}";
            ResponseEntity<String> response = restTemplate.exchange(
                url,
                HttpMethod.POST,
                new HttpEntity<>(dto, headers),
                String.class
            );
            
            if (response.getStatusCode().is2xxSuccessful()) {
                logger.info("Successfully synced ${domainObjectName} to external system. ID: {}", ${domainObjectName?uncap_first}.getId());
                return true;
            } else {
                logger.error("Failed to sync ${domainObjectName} to external system. Response: {}", response);
                return false;
            }
            
        } catch (Exception e) {
            logger.error("Error syncing to external system", e);
            return false;
        }
    }
    
    /**
     * 将外部系统DTO转换为领域对象
     */
    private ${domainObjectName} convertToDomainObject(External${domainObjectName}DTO dto) {
        ${domainObjectName} ${domainObjectName?uncap_first} = new ${domainObjectName}();
        
        // 设置基本属性
        ${domainObjectName?uncap_first}.setId(null); // 不使用外部系统ID
        ${domainObjectName?uncap_first}.setExternalId(dto.getId());
<#list fields as field>
<#if field.name != "id" && field.name != "externalId">
        ${domainObjectName?uncap_first}.set${field.name?cap_first}(dto.get${field.name?cap_first}());
</#if>
</#list>
        
        return ${domainObjectName?uncap_first};
    }
    
    /**
     * 将领域对象转换为外部系统DTO
     */
    private External${domainObjectName}DTO convertToExternalDTO(${domainObjectName} ${domainObjectName?uncap_first}) {
        External${domainObjectName}DTO dto = new External${domainObjectName}DTO();
        
        // 设置外部系统需要的属性
        dto.setId(${domainObjectName?uncap_first}.getExternalId());
<#list fields as field>
<#if field.name != "id" && field.name != "externalId">
        dto.set${field.name?cap_first}(${domainObjectName?uncap_first}.get${field.name?cap_first}());
</#if>
</#list>
        
        return dto;
    }
} 